package com.farm.iproject.service.impl;

import com.farm.iproject.domain.Appmodel;
import com.farm.iproject.domain.Dictype;
import com.farm.iproject.domain.Project;
import com.farm.core.time.TimeTool;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.iproject.dao.AppdicDaoInter;
import com.farm.iproject.dao.DictypeDaoInter;
import com.farm.iproject.dao.DoctextDaoInter;
import com.farm.iproject.dao.FieldDaoInter;
import com.farm.iproject.dao.PdocumentDaoInter;
import com.farm.iproject.dao.ProjectDaoInter;
import com.farm.iproject.service.AppmodelServiceInter;
import com.farm.iproject.service.DoctextServiceInter;
import com.farm.iproject.service.FieldServiceInter;
import com.farm.iproject.service.PopgroupServiceInter;
import com.farm.iproject.service.ProjectServiceInter;
import com.farm.parameter.FarmParameterService;
import com.farm.sfile.domain.ex.DirResouce;
import com.farm.sfile.service.FileBaseServiceInter;
import com.farm.sfile.utils.ViewDirUtils;
import com.farm.wsch.index.WschIndexFactory;
import com.farm.wsch.index.WschIndexServerInter;
import com.farm.wsch.index.WschSearchServerInter;
import com.farm.wsch.index.pojo.IndexConfig;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：检索项目服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class ProjectServiceImpl implements ProjectServiceInter {
	@Resource
	private ProjectDaoInter projectDaoImpl;
	@Resource
	private AppmodelServiceInter appModelServiceImpl;
	@Resource
	private FieldDaoInter fieldDaoImpl;
	@Resource
	private FieldServiceInter fieldServiceImpl;
	@Resource
	private PdocumentDaoInter pdocumentDaoImpl;
	@Resource
	private DictypeDaoInter dictypeDaoImpl;
	@Resource
	private AppdicDaoInter appdicDaoImpl;
	@Resource
	private DoctextDaoInter doctextDaoImpl;
	@Resource
	private PopgroupServiceInter popGroupServiceImpl;
	@Resource
	private FileBaseServiceInter fileBaseServiceImpl;
	private static final Logger log = Logger.getLogger(ProjectServiceImpl.class);

	@Override
	@Transactional
	public Project insertProjectEntity(Project entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		// entity.setCusername(user.getName());
		// entity.setEuser(user.getId());
		// entity.setEusername(user.getName());
		// entity.setEtime(TimeTool.getTimeDate14());
		if (isKeyidRepeat(entity.getKeyid(), null)) {
			throw new RuntimeException("the keyid is repeat!(" + entity.getKeyid() + ")");
		}
		if (StringUtils.isNotBlank(entity.getMinimgid())) {
			try {
				fileBaseServiceImpl.submitFile(entity.getMinimgid());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isNotBlank(entity.getMaximgid())) {
			try {
				fileBaseServiceImpl.submitFile(entity.getMaximgid());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		Project project = projectDaoImpl.insertEntity(entity);
		fieldServiceImpl.initProjectFields(project, user);
		return project;
	}

	@Override
	@Transactional
	public Project editProjectEntity(Project entity, LoginUser user) {
		Project entity2 = projectDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setKeyid(entity.getKeyid());
		entity2.setName(entity.getName());
		entity2.setSort(entity.getSort());
		if (StringUtils.isNotBlank(entity.getMinimgid())) {
			entity2.setMinimgid(entity.getMinimgid());
			try {
				fileBaseServiceImpl.submitFile(entity.getMinimgid());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			if (StringUtils.isNotBlank(entity2.getMinimgid())) {
				fileBaseServiceImpl.freeFile(entity2.getMinimgid());
			}
			entity2.setMinimgid(null);
		}
		if (StringUtils.isNotBlank(entity.getMaximgid())) {
			entity2.setMaximgid(entity.getMaximgid());
			try {
				fileBaseServiceImpl.submitFile(entity.getMaximgid());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			if (StringUtils.isNotBlank(entity2.getMaximgid())) {
				fileBaseServiceImpl.freeFile(entity2.getMaximgid());
			}
			entity2.setMaximgid(null);
		}
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		if (isKeyidRepeat(entity.getKeyid(), entity.getId())) {
			throw new RuntimeException("the keyid is repeat!(" + entity.getKeyid() + ")");
		}
		// entity2.setCuser(entity.getCuser());
		// entity2.setCtime(entity.getCtime());
		// entity2.setId(entity.getId());
		projectDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteProjectEntity(String id, LoginUser user) {
		List<Dictype> dics = dictypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", id, "=")).toList());
		for (Dictype dic : dics) {
			appdicDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("DICID", dic.getId(), "=")).toList());
			dictypeDaoImpl.deleteEntity(dic);
		}
		fieldDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", id, "=")).toList());
		List<Appmodel> models = appModelServiceImpl.getAppmodels(id);
		for (Appmodel model : models) {
			appModelServiceImpl.deleteAppmodelEntity(model.getId(), user);
		}
		pdocumentDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", id, "=")).toList());
		doctextDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", id, "=")).toList());
		Project project = projectDaoImpl.getEntity(id);
		if (StringUtils.isNotBlank(project.getMinimgid())) {
			fileBaseServiceImpl.freeFile(project.getMinimgid());
		}
		if (StringUtils.isNotBlank(project.getMaximgid())) {
			fileBaseServiceImpl.freeFile(project.getMaximgid());
		}
		projectDaoImpl.deleteEntity(project);
		popGroupServiceImpl.deletePopgourps(id, null, user);

	}

	@Override
	@Transactional
	public Project getProjectEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return projectDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createProjectSimpleQuery(DataQuery query) {
		// TODO 自动生成代码,修改后请去除本注释
		DataQuery dbQuery = DataQuery.init(query, "WSCH_P_PROJECT", "SORT,ID,KEYID,NAME,PCONTENT,PSTATE,CUSER,CTIME");
		return dbQuery;
	}

	@Override
	@Transactional
	public boolean isKeyidRepeat(String keyid, String id) {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("KEYID", keyid, "="));
		if (StringUtils.isNotBlank(id)) {
			rules.add(new DBRule("ID", id, "!="));
		}
		return projectDaoImpl.countEntitys(rules.toList()) > 0;
	}

	@Override
	@Transactional
	public String getIndexPath(String projectid) {
		Project project = getProjectEntity(projectid);
		String basepath = FarmParameterService.getInstance().getParameter("config.index.dir");
		return basepath.replace("/", File.separator).replace("\\", File.separator) + File.separator
				+ project.getKeyid();
	}

	@Override
	@Transactional
	public WschIndexServerInter getWschIndexServer(String projectid) throws IOException {
		WschIndexServerInter indexServer = WschIndexFactory.getIndexServer(getIndexConfig(projectid));
		return indexServer;
	}

	@Override
	@Transactional
	public WschSearchServerInter getWschSearchServer(String projectid) throws IOException {
		WschSearchServerInter searchServer = WschIndexFactory.getSearchServer(getIndexConfig(projectid));
		return searchServer;
	}

	@Override
	@Transactional
	public IndexConfig getIndexConfig(String projectid) {
		IndexConfig config = new IndexConfig(getIndexPath(projectid));
		return config;
	}

	@Override
	@Transactional
	public String getFilesPath(String projectid) {
		DirResouce dir = ViewDirUtils.getWriteAbleDir();
		Project project = getProjectEntity(projectid);
		return dir.getPath().replace("/", File.separator).replace("\\", File.separator) + File.separator
				+ project.getKeyid();
	}

	@Override
	@Transactional
	public List<Project> getProjects() {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("PSTATE", "2", "="));
		List<Project> projects = projectDaoImpl.selectEntitys(rules.toList());
		Collections.sort(projects, new Comparator<Project>() {
			@Override
			public int compare(Project o1, Project o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return projects;
	}

	@Override
	@Transactional
	public void mergeIndex(String projectid, LoginUser currentUser) {
		WschIndexServerInter indexServer = null;
		try {
			indexServer = WschIndexFactory.getIndexServer(getIndexConfig(projectid));
			indexServer.mergeIndex();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				indexServer.closeAndSubmit();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	@Transactional
	public Project getProjectByKey(String key) {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("KEYID", key, "="));
		List<Project> projects = projectDaoImpl.selectEntitys(rules.toList());
		if (projects.size() > 0) {
			return projects.get(0);
		} else {
			return null;
		}
	}

}
